#include <myheader.h>

/*Usage:use select  */
int main(int argc, char *argv[])
{
    char *ip = "192.168.112.129";
    char *port = "8080";
    //create a socket endpoint
    int socket_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    ERROR_CHECK(socket_fd,-1,"socket");

    //create a sockaddr_in struct
    struct sockaddr_in sockaddr_in_struct;
    sockaddr_in_struct.sin_family = AF_INET;
    sockaddr_in_struct.sin_port = htons(atoi(port));
    sockaddr_in_struct.sin_addr.s_addr = inet_addr(ip);

    //connect
    int ret = connect(socket_fd,(struct sockaddr*)&sockaddr_in_struct,
                      sizeof(sockaddr_in_struct));
    ERROR_CHECK(ret,-1,"connect");

    //send;
    char buf[60] = {0};
    fd_set select_set;
    while(1){
        //fd_set
        FD_ZERO(&select_set);
        FD_SET(socket_fd,&select_set);
        FD_SET(STDIN_FILENO,&select_set);
        int ret = select(socket_fd + 1,&select_set,NULL,NULL,NULL);
        ERROR_CHECK(ret,-1,"select");
        //select
        if(FD_ISSET(STDIN_FILENO,&select_set)){
            //send
            memset(buf, 0, sizeof(buf));
            int read_cnt = read(STDIN_FILENO,buf, sizeof(buf));
            if(read_cnt == 0){
                printf("disconnection\n");
                break;
            }
            ERROR_CHECK(read_cnt,-1,"read stdin");

            int send_cnt = send(socket_fd,buf,sizeof(buf),0);
            ERROR_CHECK(send_cnt,-1,"send");

        }else if(FD_ISSET(socket_fd,&select_set)){
            //recv
            memset(buf,0,sizeof(buf));
            int recv_cnt = recv(socket_fd,buf,sizeof(buf),0);
            if(recv_cnt == 0){
                printf("the other side disconnection\n");
                break;
            }
            ERROR_CHECK(recv_cnt,-1,"recv");

            //printf
            printf("%s",buf);
        }
    }
    close(socket_fd);

    return 0;
}

